package com.situ.cloud.gateway.conf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableOpenApi
@Primary
public class SwaggerConfig implements SwaggerResourcesProvider {

    @Autowired
    private RouteLocator routeLocator;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.situ.cloud.*.controller"))
                .paths(PathSelectors.any())
                .build().securitySchemes(mySchemes());
    }


    private List<SecurityScheme> mySchemes() {
        List<SecurityScheme> list = new ArrayList<>();
        list.add(new ApiKey("Authorization", "Authorization", "header"));
        return list;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口文档")
                .version("1.0.0")
                .description("这是描述")
                .build();
    }

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resourceList = new ArrayList<>();
//        routeLocator.getRoutes().doOnEach((routeSignal -> {
//            resourceList.add(swaggerResource(routeSignal.get().getId(), "/user/v3/api-docs", "1.0"));
//        }));
        return resourceList;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource sr = new SwaggerResource();
        sr.setName(name);
        sr.setLocation(location);
        sr.setSwaggerVersion(version);
        return sr;
    }
}
